package com.cloud.help.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloud.commonapi.jsonResult.Result;
import com.cloud.commonapi.model.Help_info;
import com.cloud.commonapi.model.User_info;
import com.cloud.help.entity.Account_HelpInfo;
import com.cloud.help.service.HelpService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * author : 黄永佳
 * create : 2019/9/29 0029 10:15
 * modified :
 * 功能 :
 **/
@RestController
@RequestMapping("/helpinfo")
@ApiOperation(value="求助业务模块")
public class HelpController {
    @Autowired
    HelpService helpService;
    @Autowired
    RestTemplate restTemplate;


    @PostMapping("")
    @ApiOperation(value = "增加求助业务")
    public Result addHelp(Help_info help_info,@RequestParam(value = "file",required = false) MultipartFile file,HttpSession session){
        Integer accountId=Integer.parseInt(session.getAttribute("loginId").toString());
        if(session.getAttribute("loginId")==null){
            return Result.build(400,"请登录");
        }
        if (file!=null) {
            String fileName = file.getOriginalFilename();  // 文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
            String filePath = "G:\\web\\html\\img\\"; // 上传后的路径
            fileName = UUID.randomUUID() + suffixName; // 新文件名
            File dest = new File(filePath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
            help_info.setPicture(fileName);
        }
        help_info.setAccountId(accountId);
        System.out.println(new Date());
        help_info.setTime(new Timestamp(new Date().getTime()));
        help_info.setStatus(1);
        if(helpService.addHelp(help_info)>0){
            return Result.build(200,"添加成功");
        }else {
            return Result.build(400,"添加失败");
        }
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据业务id查询业务信息")
    public Result selectById(@PathVariable int id){
        Account_HelpInfo account_helpInfo=helpService.selectById(id);
        JSONObject jSONObject= restTemplate.getForObject("http://USERCENTER/usercontroller/userinfo/users/"+account_helpInfo.getAccountId(),JSONObject.class);
        JSONObject  data=jSONObject.getJSONObject("data");
        User_info user_info= JSON.parseObject(data.toString(), User_info.class);
        if(account_helpInfo!=null){
            HashMap<String,Object> hashMap=new HashMap<>();
            hashMap.put("account_helpInfo",account_helpInfo);
            hashMap.put("user_info",user_info);
            return Result.buildData(202,"查询成功",hashMap);
        }else {
            return Result.build(400,"查询无相关信息");
        }
    }
    @GetMapping("/list")
    @ApiOperation(value = "查看所有业务信息")
    public Result findAll(){

        List<Account_HelpInfo> account_helpInfoList= helpService.findAll();
        if(account_helpInfoList!=null){
            HashMap<String,List<Account_HelpInfo>> hashMap=new HashMap<>();
            hashMap.put("account_helpInfoList",account_helpInfoList);
            return Result.buildData(202,"查询成功",hashMap);
        }else {
            return Result.build(200,"查询成功，列表为空");
        }
    }
    @PostMapping ("/keyword")
    @ApiOperation(value = "根据关键字查询业务")
    public Result findByKeyword(@RequestParam(required = false,defaultValue = "")String keyword){
        List<Account_HelpInfo> account_helpInfos=helpService.findByKeyword(keyword);
        if(account_helpInfos.size()!=0){
            HashMap<String,List<Account_HelpInfo>> hashMap=new HashMap<>();
            hashMap.put("account_helpInfos",account_helpInfos);
            return Result.buildData(202,"查询成功",hashMap);
        }else {
            return Result.build(200,"查询成功，列表为空");
        }
    }
    @DeleteMapping("/{id}")
    @ApiOperation(value = "下架求助业务")
    public Result delete(@PathVariable int id){
        Help_info help_info=new Help_info();
        help_info.setId(id);
        help_info.setStatus(0);
        if(helpService.update(help_info)>0){
            return Result.build(200,"下架成功");
        }else {
            return Result.build(300,"下架失败，出现异常");
        }
    }
    @ApiOperation(value="修改求助业务")
    @PutMapping("")
    public Result update(Help_info help_info,@RequestParam(value = "file",required = false) MultipartFile file,HttpSession session){
        Integer accountId=Integer.parseInt(session.getAttribute("loginId").toString());
        if(session.getAttribute("loginId")==null){
            return Result.build(400,"请登录");
        }
        if (file!=null) {
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = "G:\\web\\html\\img\\"; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        help_info.setPicture(fileName);
        }
        help_info.setTime(new Date());
        if(helpService.update(help_info)>0){
            return Result.build(200,"修改成功");
        }else {
            return Result.build(400,"修改失败，出现异常");
        }
    }
    @ApiOperation(value = "根据accountId查询业务")
    @GetMapping("/accountId")
    public Result findByAccountId(HttpSession session){
        if(session.getAttribute("loginId")==null) {
            return Result.build(400, "请登录");
        }

        List<Account_HelpInfo> account_helpInfos=helpService.findByAccountId(Integer.parseInt(session.getAttribute("loginId").toString()));
        if(account_helpInfos!=null){
            HashMap<String,List<Account_HelpInfo>> hashMap=new HashMap<>();
            hashMap.put("account_helpInfos",account_helpInfos);
            return Result.buildData(202,"查询成功",hashMap);
        }else {
            return Result.build(400,"查询成功，列表为空");
        }
    }

}
